package com.zyit.util;


import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class BeanRowMapper<T> implements RowMapper<T> {

    private Class<T> clazz;

    public BeanRowMapper(Class<T> clazz){
        this.clazz = clazz;

    }


    @Override
    public T mapperRow(ResultSet rs) throws SQLException {
        T t= null;
        //获取类的实例
        try {
            t = clazz.getDeclaredConstructor().newInstance();


            //获取查询列数
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            for(int i = 1;i <= columnCount;i++){
                String columnLabel = metaData.getColumnLabel(i);

                //拼装set方法
                String methodStr = "set"+columnLabel.substring(0,1).toUpperCase()+columnLabel.substring(1);

                //执行set方法
                Method[] methods = clazz.getMethods();
                //迭代匹配 匹配上了执行 否则不执行
                for(Method method : methods){
                    if(method.getName().equals(methodStr)){
                        method.invoke(t,rs.getObject(columnLabel));
                        break;
                    }
                }

            }
        }  catch (Exception e) {
            e.printStackTrace();
        }


        return t;
    }
}